

export class filterTools
{
    constructor(page)
    {
        this.page = page ;
    }

    async getWindowDimensions()
    {
        const windowDimensions = await this.page.ref.evaluate(()=>{
            return{
                width: window.innerWidth,
                height: window.innerHeight
            };
        });
        return windowDimensions ;
    }

    getRidOfUselessDivs(elem)
    {
        if(elem['tag'] == 'div')
        {
            if(!elem['role'] && !elem['itsOwnText']) return true ;
            if(elem['role'] && elem['role'] != 'textbox' && elem['role'] != 'button') return true ;
            if(elem.itsOwnText?.trim().length === 0) return true ;
        }
        return false ;
    }

    getRidOfNulls(elem)
    {
        const res = {} ;
        res.boundingBox = elem.boundingBox; 

        if(this.getRidOfUselessDivs(elem)) return {skip:true};

        for(const key in elem)
        {
            if(elem[key])
            {
                res[key] = elem[key] ;
                if(key == 'href') res.href = elem.href.slice(0,50) ;
                if(key == 'innerText') res.innerText = elem.innerText.slice(0,300);
            } 
        }
        return res;
    }

    testBoxDimensions(elem, windowWidth, windowHeight)
    {
        const {boundingBox: box} = elem ;

        if(box.width * box.height <= 36) return false;

        return (box.x >= 0 && box.y >= 0 && 
            box.x + box.width <= windowWidth && 
            box.y + box.height <= windowHeight) ;
    }

    async filterScrapedElements(elements)
    {
        const {width: windowWidth, height: windowHeight} = await this.getWindowDimensions() ;
        const result = [] ;
        for(const element of elements)
        {
            if(this.testBoxDimensions(element,windowWidth,windowHeight))
            {
                const withoutNulls = this.getRidOfNulls(element) ;
                if(withoutNulls.skip) continue; 
                result.push(withoutNulls) ;
            }
        }
        return result ;
    }
}